/*
 * Copyright (c) 2006-2011, Petr Panteleyev
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 *    1. Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *    2. Redistributions in binary form must reproduce the above copyright notice,
 *       this list of conditions and the following disclaimer in the documentation
 *       and/or other materials provided with the distribution.
 *    3. The name of the author may not be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package org.panteleyev.blogclient;

import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.net.URLConnection;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import org.panteleyev.html.HTMLImageDialog;
import org.panteleyev.swing.BasicDialog;
import org.panteleyev.swing.ClipboardUtil;
import org.panteleyev.swing.OkCancelButtonPanel;
import org.panteleyev.swing.SwingFactory;
import org.panteleyev.swing.SwingWorkerEx;

public final class ImageReferenceDialog extends BasicDialog<JFrame> implements HTMLImageDialog {
    private javax.swing.JCheckBox           _linkToOriginalCheckBox;
    private javax.swing.JComboBox<String>   alignComboBox;
    private javax.swing.JTextField          borderEdit;
    private javax.swing.JButton             detectSizeButton;
    private javax.swing.JTextField          heightEdit;
    private javax.swing.JTextField          linkTitleText;
    private javax.swing.JTextField          referenceTextEdit;
    private javax.swing.JTextField          urlTextEdit;
    private javax.swing.JTextField          widthEdit;

    private String                          url;
    private String                          refText;

    private class ImageSizeThread extends SwingWorkerEx<Object,Object> {
        private BufferedImage bim;

        ImageSizeThread(Window wnd) {
            super(wnd);
        }

        @Override
        protected Object doInBackground() throws Exception {
            try {
                URL url = new URL(urlTextEdit.getText());
                URLConnection conn = url.openConnection();
                bim = javax.imageio.ImageIO.read(conn.getInputStream());
            } catch (Exception e) {
                setException(e);
            }

            return null;
        }

        @Override
        protected void done() {
            if (getException() != null) {
                MainClass.handleException(null, getException());
            } else {
                widthEdit.setText(Integer.toString(bim.getWidth()));
                heightEdit.setText(Integer.toString(bim.getHeight()));
            }

            super.done();
        }
    }

    public ImageReferenceDialog(JFrame owner) {
        super(owner);
        this.url = ClipboardUtil.getAsUrl();
        initComponents();
    }

    public ImageReferenceDialog(JFrame owner, String url) {
        super(owner);
        this.url = url;
        initComponents();
    }

    @Override
    public void dataToControls() {
        this.referenceTextEdit.setText(this.refText);
        this.urlTextEdit.setText(this.url);
        this.linkTitleText.setText(null);
        this.widthEdit.setText(null);
        this.heightEdit.setText(null);
        this.borderEdit.setText(null);

        pack();
    }

    @Override
    public String getReference() {
        int width = parseInt(widthEdit);
        int height = parseInt(heightEdit);
        int border = parseInt(borderEdit);

        String urlText = urlTextEdit.getText();

        StringBuilder b = new StringBuilder();

        boolean original = _linkToOriginalCheckBox.isSelected();

        if (original) {
            b.append("<a href='").append(urlText).append("'>");
        }

        b.append("<img src='").append(urlText).append("'");

        if (width != 0) {
            b.append(" width='").append(Integer.toString(width)).append("'");
        }

        if (height != 0) {
            b.append(" height='").append(Integer.toString(height)).append("'");
        }

        if (border >= 0) {
            b.append(" border='").append(Integer.toString(border)).append("'");
        }

        String title = linkTitleText.getText();
        if (title.length() != 0) {
            b.append(" title='").append(title).append("'");
        }

        String text = referenceTextEdit.getText();
        if (text.length() != 0) {
            b.append(" alt='").append(text).append("'");
        }

        String align = (String)this.alignComboBox.getSelectedItem();
        if ((align != null) && (align.length() != 0)) {
            b.append(" align='").append(align).append("'");
        }

        b.append(">");

        if (original) {
            b.append("</a>");
        }

        return b.toString();
    }

    @Override
    public void setUrl(String url) {
        this.url = url;
    }

    @Override
    public String getUrl() {
        return urlTextEdit.getText();
    }

    @Override
    public void setAltText(String text) {
        this.refText = text;
    }

    @Override
    public boolean isLinkToOriginal() {
        return _linkToOriginalCheckBox.isSelected();
    }

    private void initComponents() {
        setTitle(L10N.IMRD_TITLE.s());
        getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.PAGE_AXIS));

        JPanel mainPanel = SwingFactory.createPanel(
            BorderFactory.createEmptyBorder(10, 10, 10, 10), SwingFactory.LAYOUT.BOX_Y,
            /* Alternate Text */
            new JLabel(L10N.IMRD_ALT_TEXT_LABEL.s()),
            Box.createVerticalStrut(3),
            referenceTextEdit = new JTextField(40),
            Box.createVerticalStrut(5),
            /* Link Title */
            new JLabel(L10N.IMRD_LINK_TITLE_LABEL.s()),
            Box.createVerticalStrut(3),
            linkTitleText = new JTextField(40),
            Box.createVerticalStrut(5),
            /* URL */
            new JLabel("URL"),
            Box.createVerticalStrut(3),
            urlTextEdit = new JTextField(40),
            Box.createVerticalStrut(3),
            _linkToOriginalCheckBox = new JCheckBox(L10N.IMRD_LINK_TO_ORIGINAL_CHECKBOX.s()),
            Box.createVerticalStrut(5),
            /* Size */
            SwingFactory.createPanel(null, SwingFactory.LAYOUT.BOX_X,
                new JLabel(L10N.IMRD_WIDTH_LABEL.s()),
                Box.createHorizontalStrut(3),
                widthEdit = new JTextField(4),
                Box.createHorizontalStrut(5),
                new JLabel(L10N.IMRD_HEIGHT_LABEL.s()),
                Box.createHorizontalStrut(3),
                heightEdit = new JTextField(4),
                Box.createHorizontalStrut(5),
                new JLabel(L10N.IMRD_BORDER_LABEL.s()),
                Box.createHorizontalStrut(3),
                borderEdit = new JTextField(2),
                Box.createHorizontalStrut(5),
                new JLabel(L10N.IMRD_ALIGN_LABEL.s()),
                Box.createHorizontalStrut(3),
                alignComboBox = new JComboBox<>(new String[] {
                    "", "Bottom", "Top", "Middle", "Left", "Right", "Absmiddle", "Absbottom", "Center", "Texttop"
                })
            ),
            Box.createVerticalStrut(3),
            detectSizeButton = new JButton(L10N.IMRD_DETECT_SIZE_BUTTON.s())
        );

        detectSizeButton.setFocusPainted(false);
        detectSizeButton.setFocusable(false);
        detectSizeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                new ImageSizeThread(ImageReferenceDialog.this).execute();
            }
        });

        SwingFactory.setAlignmentX(mainPanel, LEFT_ALIGNMENT);
        getContentPane().add(mainPanel);
        getContentPane().add(new OkCancelButtonPanel(this, JComponent.LEFT_ALIGNMENT));

        pack();
    }
}
